import axios from 'axios';
import Vue from 'vue';
const service = axios.create({
    // process.env.NODE_ENV === 'development' 来判断是否开发环境
    baseURL: 'http://47.99.44.146:6534',
    timeout: 5000
});
//当前ajax请求队列
let pending = [];
let cancelToken = axios.CancelToken;
//清除请求
let removePending = (config) => { 
    for(let i in pending){
        if(pending[i].url === config.url) { 
            
            pending[i].f();
            pending.splice(i, 1);
            
        }
    }
    
}
service.interceptors.request.use(
    config => {
        removePending(config); //在一个axios发送前执行一下判定操作，在removePending中执行取消操作
            
        config.cancelToken = new cancelToken(function executor(c){//本次axios请求的配置添加cancelToken
            pending.push({
                url: config.url,
                f:c
            });
            Vue.prototype.$httpRequestList.push(c);
        });
        return config;
    },
    error => {
        console.log(error);
        return Promise.reject();
    }
);

service.interceptors.response.use(
    response => {
        removePending(response.config)
        if (response.status === 200) {
            return response.data;
        } else {
            Promise.reject();
        }
    },
    error => {
        
        return Promise.reject();
    }
);

export default service;
